// ==UserScript==
// @name         继续教育网课自动刷课脚本-专用于xuexi.jsou.cn
// @namespace    http://tampermonkey.net/
// @version      1.2
// @description  继续教育网课助手，自动播放视频，自动完成课程，25分钟自动刷新
// @author       Your Name
// @match        *://xuexi.jsou.cn/jxpt-web/student/activity/display*
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    // 日志功能
    const logger = {
        debug: function(message) {
            console.log(`%c [继续教育网课助手] ${message}`, 'color: green;');
        },
        info: function(message) {
            console.log(`[继续教育网课助手] ${message}`);
        },
        warn: function(message) {
            console.warn(`[继续教育网课助手] ${message}`);
        },
        error: function(message, error) {
            console.error(`[继续教育网课助手] ${message}`, error);
        }
    };

    // 用户配置
    const userConfig = {
        autoPlay: true,          // 自动播放视频
        playbackRate: 2,         // 播放速度
        muted: false,            // 是否静音
        checkInterval: 1000,     // 检查间隔（毫秒）
        autoRefresh: true,       // 自动刷新页面
        refreshInterval: 25 * 60 * 1000, // 刷新间隔（25分钟）
        forcePlayInterval: 3000, // 视频强制播放尝试间隔（毫秒）
        jsouMode: true           // 专为继续教育网课平台优化
    };

    // 创建控制面板
    function createControlPanel() {
        const panel = document.createElement('div');
        panel.style.position = 'fixed';
        panel.style.top = '10px';
        panel.style.right = '10px';
        panel.style.backgroundColor = '#f8f9fa';
        panel.style.border = '1px solid #ddd';
        panel.style.borderRadius = '5px';
        panel.style.padding = '10px';
        panel.style.zIndex = '9999';
        panel.style.width = '220px';
        panel.style.boxShadow = '0 0 10px rgba(0,0,0,0.1)';

        // 添加标题
        const title = document.createElement('h3');
        title.textContent = '继续教育网课助手';
        title.style.margin = '0 0 10px 0';
        title.style.padding = '0 0 5px 0';
        title.style.borderBottom = '1px solid #ddd';
        title.style.fontSize = '14px';
        title.style.textAlign = 'center';
        panel.appendChild(title);

        // 添加播放速度控制
        const speedContainer = document.createElement('div');
        speedContainer.style.margin = '5px 0';
        speedContainer.style.display = 'flex';
        speedContainer.style.alignItems = 'center';
        speedContainer.style.justifyContent = 'space-between';

        const speedLabel = document.createElement('span');
        speedLabel.textContent = '播放速度:';
        speedLabel.style.fontSize = '12px';
        speedContainer.appendChild(speedLabel);

        const speedSelect = document.createElement('select');
        speedSelect.style.width = '100px';
        speedSelect.style.padding = '2px';
        speedSelect.style.borderRadius = '3px';

        [0.5, 1, 1.5, 2, 3, 4, 5].forEach(speed => {
            const option = document.createElement('option');
            option.value = speed;
            option.textContent = `${speed}x`;
            option.selected = speed === userConfig.playbackRate;
            speedSelect.appendChild(option);
        });

        speedSelect.addEventListener('change', function() {
            userConfig.playbackRate = parseFloat(this.value);
            logger.info(`播放速度已设置为 ${userConfig.playbackRate}x`);

            // 修改视频速度
            updateVideoSpeed(userConfig.playbackRate);
        });

        speedContainer.appendChild(speedSelect);
        panel.appendChild(speedContainer);

        // 添加自动播放开关
        const autoPlayContainer = document.createElement('div');
        autoPlayContainer.style.margin = '5px 0';
        autoPlayContainer.style.display = 'flex';
        autoPlayContainer.style.alignItems = 'center';
        autoPlayContainer.style.justifyContent = 'space-between';

        const autoPlayLabel = document.createElement('span');
        autoPlayLabel.textContent = '自动播放:';
        autoPlayLabel.style.fontSize = '12px';
        autoPlayContainer.appendChild(autoPlayLabel);

        const autoPlayCheckbox = document.createElement('input');
        autoPlayCheckbox.type = 'checkbox';
        autoPlayCheckbox.checked = userConfig.autoPlay;
        autoPlayCheckbox.addEventListener('change', function() {
            userConfig.autoPlay = this.checked;
            logger.info(`自动播放已${userConfig.autoPlay ? '开启' : '关闭'}`);

            // 根据自动播放设置控制视频
            if (userConfig.autoPlay) {
                startVideoPlayback();
            }
        });

        autoPlayContainer.appendChild(autoPlayCheckbox);
        panel.appendChild(autoPlayContainer);

        // 添加静音开关
        const muteContainer = document.createElement('div');
        muteContainer.style.margin = '5px 0';
        muteContainer.style.display = 'flex';
        muteContainer.style.alignItems = 'center';
        muteContainer.style.justifyContent = 'space-between';

        const muteLabel = document.createElement('span');
        muteLabel.textContent = '静音:';
        muteLabel.style.fontSize = '12px';
        muteContainer.appendChild(muteLabel);

        const muteCheckbox = document.createElement('input');
        muteCheckbox.type = 'checkbox';
        muteCheckbox.checked = userConfig.muted;
        muteCheckbox.addEventListener('change', function() {
            userConfig.muted = this.checked;
            logger.info(`静音已${userConfig.muted ? '开启' : '关闭'}`);

            // 根据静音设置控制视频
            updateVideoMute(userConfig.muted);
        });

        muteContainer.appendChild(muteCheckbox);
        panel.appendChild(muteContainer);

        // 添加自动刷新开关
        const refreshContainer = document.createElement('div');
        refreshContainer.style.margin = '5px 0';
        refreshContainer.style.display = 'flex';
        refreshContainer.style.alignItems = 'center';
        refreshContainer.style.justifyContent = 'space-between';

        const refreshLabel = document.createElement('span');
        refreshLabel.textContent = '自动刷新:';
        refreshLabel.style.fontSize = '12px';
        refreshContainer.appendChild(refreshLabel);

        const refreshCheckbox = document.createElement('input');
        refreshCheckbox.type = 'checkbox';
        refreshCheckbox.checked = userConfig.autoRefresh;
        refreshCheckbox.addEventListener('change', function() {
            userConfig.autoRefresh = this.checked;
            logger.info(`自动刷新已${userConfig.autoRefresh ? '开启' : '关闭'}`);

            // 重置刷新计时器
            if (userConfig.autoRefresh) {
                resetRefreshTimer();
            } else {
                clearRefreshTimer();
            }
        });

        refreshContainer.appendChild(refreshCheckbox);
        panel.appendChild(refreshContainer);

        // 添加刷新计时显示
        const timerContainer = document.createElement('div');
        timerContainer.style.margin = '5px 0';
        timerContainer.style.display = 'flex';
        timerContainer.style.alignItems = 'center';
        timerContainer.style.justifyContent = 'space-between';

        const timerLabel = document.createElement('span');
        timerLabel.textContent = '下次刷新:';
        timerLabel.style.fontSize = '12px';
        timerContainer.appendChild(timerLabel);

        const timerDisplay = document.createElement('span');
        timerDisplay.id = 'refresh-timer-display';
        timerDisplay.textContent = '已禁用';
        timerDisplay.style.fontSize = '12px';
        timerContainer.appendChild(timerDisplay);

        panel.appendChild(timerContainer);

        // 状态显示区域
        const statusContainer = document.createElement('div');
        statusContainer.style.margin = '5px 0';
        statusContainer.style.padding = '5px';
        statusContainer.style.border = '1px solid #ddd';
        statusContainer.style.borderRadius = '3px';
        statusContainer.style.backgroundColor = '#fff';
        statusContainer.style.fontSize = '12px';
        statusContainer.id = 'video-assistant-status';
        statusContainer.textContent = '等待视频加载...';
        panel.appendChild(statusContainer);

        // 添加到页面
        document.body.appendChild(panel);
        logger.info('控制面板已创建');
    }

    // 更新控制面板状态
    function updateStatus(message) {
        const statusElement = document.getElementById('video-assistant-status');
        if (statusElement) {
            statusElement.textContent = message;
        }
    }

    // 更新视频速度
    function updateVideoSpeed(speed) {
        try {
            // 尝试VideoJS方式
            if (typeof videojs !== 'undefined') {
                const player = getVideoJSPlayer();
                if (player && typeof player.playbackRate === 'function') {
                    player.playbackRate(speed);
                    logger.info(`VideoJS播放速度已设置为 ${speed}x`);
                    return true;
                }
            }

            // 尝试原生方式
            const video = getVideoElement();
            if (video) {
                video.playbackRate = speed;
                logger.info(`原生视频播放速度已设置为 ${speed}x`);
                return true;
            }

            return false;
        } catch (e) {
            logger.error('设置播放速度时出错', e);
            return false;
        }
    }

    // 更新视频静音状态
    function updateVideoMute(muted) {
        try {
            // 尝试VideoJS方式
            if (typeof videojs !== 'undefined') {
                const player = getVideoJSPlayer();
                if (player && typeof player.muted === 'function') {
                    player.muted(muted);
                    logger.info(`VideoJS ${muted ? '已静音' : '已取消静音'}`);
                    return true;
                }
            }

            // 尝试原生方式
            const video = getVideoElement();
            if (video) {
                video.muted = muted;
                logger.info(`原生视频 ${muted ? '已静音' : '已取消静音'}`);
                return true;
            }

            return false;
        } catch (e) {
            logger.error('设置静音状态时出错', e);
            return false;
        }
    }

    // 获取VideoJS播放器实例
    function getVideoJSPlayer() {
        try {
            if (typeof videojs === 'undefined') {
                return null;
            }

            // 尝试不同方式获取播放器实例
            return videojs.getPlayers()['example_video_1'] ||
                   videojs('example_video_1') ||
                   videojs(document.querySelector('.video-js'));
        } catch (e) {
        };

        // 尝试特定选择器
        for (const selector of specificSelectors) {
            // 检查是否是iframe选择器
            if (selector.includes('iframe')) {
                const iframes = document.querySelectorAll(selector);
                for (const iframe of iframes) {
                    try {
                        // 尝试从 iframe 内部获取视频
                        const iframeVideo = iframe.contentDocument?.querySelector('video');
                        if (iframeVideo) return iframeVideo;
                    } catch (e) {
                        // 跨域限制可能会造成错误，忽略
                    }
                }
                continue;
            }

            const elements = document.querySelectorAll(selector);
            for (const element of elements) {
                if (element instanceof HTMLVideoElement) {
                    logger.info(`找到视频元素: ${selector}`);
                    return element;
                }
            }
        }

        // 最后尝试获取任何视频元素
        const videos = document.querySelectorAll('video');
        if (videos.length > 0) {
            logger.info(`找到 ${videos.length} 个视频元素`);
            return videos[0]; // 返回第一个视频元素
        }

        logger.warn('未找到视频元素');
        return null;
    } catch (e) {
        logger.error('获取视频元素时出错', e);
        return null;
    }
}
            if (iframes.length > 0) {
                logger.info(`找到${iframes.length}个iframe，尝试处理`);
                
                iframes.forEach((iframe, index) => {
                    try {
                        const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                        const iframeVideos = iframeDoc.querySelectorAll('video');
                        
                        if (iframeVideos.length > 0) {
                            logger.info(`在iframe ${index+1}中找到${iframeVideos.length}个视频`);
                            
                            iframeVideos.forEach(video => {
                                video.autoplay = true;
                                video.muted = true;
                                video.playbackRate = userConfig.playbackRate;
                                video.play().catch(() => {
                                    // 忽略错误
                                });
                            });
                            
                            // 尝试点击iframe内的播放按钮
                            const playButtons = iframeDoc.querySelectorAll('.vjs-big-play-button, .vjs-play-control, [class*="play"]');
                            playButtons.forEach(button => {
                                try {
                                    button.click();
                                } catch (e) { /* 忽略错误 */ }
                            });
                        }
                    } catch (e) {
                        // 跨域iframe会出错，忽略
                    }
                });
            }
            
            // 3. 点击所有可能的播放按钮
            clickJsouPlayButtons();
            
            // 4. 注入特殊方法
            injectJsouAutoplay();
            
        } catch (e) {
            logger.error('继续教育网课特殊处理出错', e);
        }
    }
    
    // 点击继续教育网课平台的播放按钮
    function clickJsouPlayButtons() {
        // 适配继续教育网课平台的选择器
        const jsouButtonSelectors = [
            '.vjs-big-play-button',
            '.vjs-play-control',
            '.videoArea .video-js .vjs-play-control',
            '.player-button',
            '.player-content .play-button',
            '[class*="playButton"]',
            '[class*="play-button"]',
            '[class*="video-play"]',
            'button.play',
            'button[title*="播放"]',
            '.btn-play',
            '.mejs-play',
            '.jw-icon-playback'
        ];
        
        // 点击按钮
        let buttonFound = false;
        jsouButtonSelectors.forEach(selector => {
            document.querySelectorAll(selector).forEach(button => {
                try {
                    logger.info(`点击播放按钮: ${selector}`);
                    button.click();
                    buttonFound = true;
                } catch (e) {
                    // 忽略错误
                }
            });
        });
        
        // 尝试播放区域点击
        if (!buttonFound) {
            const playAreas = document.querySelectorAll('.videoArea, .player-container, .video-container, .video-js');
            playAreas.forEach(area => {
                try {
                    logger.info('点击播放区域');
                    area.click();
                } catch (e) {
                    // 忽略错误
                }
            });
        }
        
        // 尝试键盘空格键触发
        try {
            document.dispatchEvent(new KeyboardEvent('keydown', {
                key: ' ',
                keyCode: 32,
                which: 32,
                bubbles: true
            }));
            logger.info('模拟空格键点击');
        } catch (e) {
            // 忽略错误
        }
    }
    
    // 注入专门针对继续教育网课的自动播放处理脚本
    function injectJsouAutoplay() {
        try {
            const scriptContent = `
                // 覆盖视频元素的原始pause方法，防止暂停
                if (!window._jsouHelperInjected) {
                    window._jsouHelperInjected = true;
                    
                    // 保存原始方法
                    const originalPlay = HTMLVideoElement.prototype.play;
                    const originalPause = HTMLVideoElement.prototype.pause;
                    
                    // 重写play方法，确保播放速度设置
                    HTMLVideoElement.prototype.play = function() {
                        this.playbackRate = ${userConfig.playbackRate};
                        return originalPlay.apply(this, arguments);
                    };
                    
                    // 重写pause方法，在特定条件下阻止暂停
                    HTMLVideoElement.prototype.pause = function() {
                        // 只有在视频结束时才允许暂停
                        if (this.ended) {
                            return originalPause.apply(this, arguments);
                        }
                        // 否则重新开始播放
                        this.playbackRate = ${userConfig.playbackRate};
                        originalPlay.apply(this, arguments);
                    };
                    
                    // 监控所有视频元素
                    setInterval(() => {
                        document.querySelectorAll('video').forEach(video => {
                            if (video.paused && !video.ended) {
                                video.playbackRate = ${userConfig.playbackRate};
                                video.play();
                            }
                        });
                    }, 1000);
                    
                    console.log('[继续教育网课助手] 视频控制脚本注入成功');
                }
            `;
            
            // 创建并注入脚本
            const scriptElement = document.createElement('script');
            scriptElement.textContent = scriptContent;
            document.head.appendChild(scriptElement);
            
            // 移除脚本元素（已执行）
            scriptElement.remove();
            
            logger.info('注入自动播放控制脚本成功');
        } catch (e) {
            logger.error('注入自动播放控制脚本失败', e);
        }
    }

    // 设置定时器，多次尝试查找和播放视频
    let findVideoAttempts = 0;
    const findVideoInterval = setInterval(() => {
        findVideoAttempts++;
        logger.info(`尝试查找视频 (第${findVideoAttempts}次)`);
        
        const video = getVideoElement();
        if (video) {
            clearInterval(findVideoInterval);
            logger.info('找到视频元素，开始处理');
            
            // 移除多余的视频覆盖层
            removeVideoOverlays();
            
            // 启动视频监控
            monitorVideoProgress();
            
            // 根据用户配置设置视频播放
            if (userConfig.autoPlay) {
                startVideoPlayback();
            }
            
            // 启动主循环
            mainLoop();
        } else if (findVideoAttempts >= 20) { // 尝试10秒后仍然没有找到视频，使用原有方式
            clearInterval(findVideoInterval);
            logger.warn('在多次尝试后未找到视频元素，切换到备用方法');
            
            // 等待VideoJS加载后开始处理
            waitForVideoJS(function(videoReady) {
                if (videoReady) {
                    logger.info('VideoJS已加载');
                } else {
                    logger.warn('等待VideoJS超时，尝试其他方法');
                }
                
                // 移除多余的视频覆盖层
                removeVideoOverlays();
                
                // 启动视频监控
                monitorVideoProgress();
                
                // 根据用户配置设置视频播放
                if (userConfig.autoPlay) {
                    startVideoPlayback();
                    
                    // 针对xuexi.jsou.cn的特殊处理
                    setTimeout(forceSjsuVideoPlay, 1000);
                }
                
                // 启动主循环
                mainLoop();
            });
        }
    }, 500); // 每0.5秒尝试一次
}

// 在页面加载完成后启动脚本
if (document.readyState === 'complete') {
    init();
} else {
    window.addEventListener('load', init);
}
    } else {
        window.addEventListener('load', init);
    }
})();
